package com.siti.kindnessplatform.aspect;

import com.siti.kindnessplatform.common.CommonResult;
import com.siti.kindnessplatform.common.ConstantYmlValue;
import com.siti.kindnessplatform.config.EasyCache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
@Component
@Aspect
public class RequestLimitAspect {

    @Autowired
    ConstantYmlValue constantYmlValue;

    @Resource
    EasyCache easyCache;

    private static final Logger logger = LoggerFactory.getLogger("RequestLimitAspect");

    @Around("within(@org.springframework.web.bind.annotation.RestController *) && @annotation(limit)")
    public Object requestLimit(final ProceedingJoinPoint proceedingJoinPoint, RequestLimit limit){
        try {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            //从获取RequestAttributes中获取HttpServletRequest的信息
            HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
            String ip = request.getRemoteAddr();
            if(ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip= inet.getHostAddress();
            }
            String url = request.getRequestURI().replace("/","");
            String key = "req_limit_".concat(url).concat(ip);
            RedissonClient redisson=easyCache.redisson;
            RAtomicLong num = redisson.getAtomicLong(key);
            long cre=num.incrementAndGet();
            if(cre==1){
                num.expire(constantYmlValue.getLimitSecond(),TimeUnit.SECONDS);
            }
            if(cre>limit.maxCount()){
                logger.error("请求次数超过限制");
                return new CommonResult("error","操作太过频繁，请稍后操作");
            }else{
                Object[] args = proceedingJoinPoint.getArgs();//得到方法执行所需的参数
                return proceedingJoinPoint.proceed(args);
            }
        } catch (Exception e) {
            logger.error("发生异常{}", e);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return new CommonResult("error","请求失败");
    }
}
